package com.bothin.experiment4.controller;

import com.bothin.experiment4.dto.ContactDTO;
import com.bothin.experiment4.dto.ContactDetailDTO;
import com.bothin.experiment4.enums.ContactStatusEnum;
import com.bothin.experiment4.enums.ProductFormStatusEnum;
import com.bothin.experiment4.enums.ProductFormTypeEnum;
import com.bothin.experiment4.enums.ResultEnum;
import com.bothin.experiment4.exception.SellException;
import com.bothin.experiment4.form.ContactForm;
import com.bothin.experiment4.model.*;
import com.bothin.experiment4.service.*;
import com.bothin.experiment4.utils.KeyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by bothin
 * At 2019/12/17 0:35
 * Description:
 */
@Controller
@RequestMapping("/contact")
@Slf4j
@Secured("ROLE_USER_ADMIN")
public class ContactController {
    @Autowired
    private IContactService contactService;

    @Autowired
    private IContactDetailService contactDetailService;

    @Autowired
    private IProductFormService productFormService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    IProductService productService;

    @GetMapping("/list")
    @ResponseBody
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "size", defaultValue = "8") Integer size,
                             @RequestParam(value = "keyword", defaultValue = "") String keyword,
                             Map<String, Object> map){
        PageHelper.startPage(page,size);
        List<ContactDTO> contactDTOS = null;
        if (!StringUtils.isEmpty(keyword)){
            contactDTOS = contactService.findByKeywordDTO(keyword);
            map.put("key","&keyword="+keyword);
        }else {
            contactDTOS = contactService.findALLDTO();
        }

        PageInfo<ContactDTO> pageInfo = new PageInfo<>(contactDTOS);
        map.put("pageInfo",pageInfo);
        return new ModelAndView("/contact/list",map);
    }

    @RequestMapping("/to/detail")
    public ModelAndView toDetail(@RequestParam(value = "contactId") String contactId,
                              Map<String, Object> map){
        ContactDTO contactDTO = contactService.findByIdDTO(contactId);
        contactDTO.setContactDetailDTOList(contactDetailService.findByContactId(contactId));
        contactDTO.setProductFormDTOList(productFormService.findByContactIdDTO(contactId));
        map.put("contactDTO", contactDTO);
        return new ModelAndView("contact/detail",map);
    }
    @RequestMapping("/to/productFrom")
    public ModelAndView toProductFrom(@RequestParam(value = "contactId") String contactId,
                                      @RequestParam(value = "productId") String productId,
                              Map<String, Object> map){
        ContactDetailDTO contactDetailDTO = contactDetailService.findByContactIdAndProductIdDTO(contactId, productId);
        if (contactDetailDTO!=null)
            map.put("contactDetailDTO", contactDetailDTO);
        return new ModelAndView("contact/productForm",map);
    }

    /**
     * 生成发货单
     * @param contactId
     * @param productId
     * @param count
     * @param session
     * @return
     */
    @RequestMapping("/productForm")
    @Transactional
    public ModelAndView productForm(@RequestParam(value = "contactId") String contactId,
                                    @RequestParam(value = "productId") String productId,
                                    @RequestParam(value = "count") Integer count, HttpSession session){
        if (StringUtils.isEmpty(contactId)||StringUtils.isEmpty(productId)){
            log.error("【生成发货单】参数不正确，contactId={}，productId={}",contactId,productId);
            throw new SellException(ResultEnum.PARAM_ERROR,"/contact/list");
        }
        ContactDetail contactDetail = contactDetailService.findByContactIdAndProductId(contactId, productId);
        if (contactDetail==null){
            log.error("【生成发货单】参数不正确，查不到contactDetail，contactId={}，productId={}",contactId,productId);
            throw new SellException(ResultEnum.PARAM_ERROR,"/contact/list");
        }
        if (contactDetail.getPrintStatus()<count){
            log.error("【生成发货单】输入数量参数不正确，剩余={}，count={}",contactDetail.getPrintStatus(),count);
            throw new SellException(ResultEnum.PARAM_ERROR,"/contact/list");
        }
        //减去
        contactDetail.setPrintStatus(contactDetail.getPrintStatus()-count);
        contactDetailService.update(contactDetail);
        //生成发货单
        productFormService.insert(new ProductForm(KeyUtil.genUniqueKey(),contactId,productId,
                count, ProductFormTypeEnum.OUT_FORM.getCode(), ProductFormStatusEnum.UNFINISHED.getCode()));
        //改履行状态
        Contact contact = contactService.findById(contactId);
        if (contact.getPerformanceStatus()==ContactStatusEnum.NOT_PERFORMANCE.getCode()){
            contact.setPerformanceStatus(ContactStatusEnum.IN_PERFORMANCE.getCode());
            contactService.update(contact);
        }
        
        String page = "";
        if (session.getAttribute("contact_page")!=null)
            page = "?page="+ session.getAttribute("contact_page");
        return new ModelAndView("redirect:/contact/list"+page);
    }

    @RequestMapping("/to/add")
    public ModelAndView toAdd(@RequestParam(value = "contactId",required = false) String contactId,
                              Map<String, Object> map){
        List<Customer> customers = customerService.findAll();
        List<Employee> salesmans = employeeService.findAllSalesmansUsable();
        List<Product> products = productService.findAll();
        map.put("customers", customers);
        map.put("salesmans", salesmans);
        map.put("products", products);
        if (!StringUtils.isEmpty(contactId)){
            ContactDTO contactDTO = contactService.findByIdDTO(contactId);
            contactDTO.setContactDetailDTOList(contactDetailService.findByContactId(contactId));
            map.put("contactDTO", contactDTO);
            //若是修改 则查出全部销售员（包括的注销帐号）
            List<Employee> allSalesmans = employeeService.findAllSalesmans();
            map.put("salesmans", allSalesmans);
        }
        return new ModelAndView("contact/add",map);
    }

    @PostMapping("/add")
    @Transactional
    public ModelAndView add(@Valid ContactForm contactForm, BindingResult bindingResult, HttpSession session) throws ParseException {
        String page = "";
        System.out.println(contactForm);
        if (bindingResult.hasErrors()){
            log.error("【创建修改合同】参数不正确, contactForm={}", contactForm);
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage(),"/contact/list");
        }
        int sum = 0;  //总金额
        for (int i = 0; i < contactForm.getProductId().length; i++) {
            if (contactForm.getProductQuantity()[i]!=null){
                sum += productService.selectPriceByProductId(contactForm.getProductId()[i]) * contactForm.getProductQuantity()[i];
            }
        }
        contactForm.setMoney(BigDecimal.valueOf(sum));
        if (StringUtils.isEmpty(contactForm.getContactId())){
            contactForm.setContactId(KeyUtil.genUniqueKey());
            contactService.insertByForm(contactForm);
            contactDetailService.insertByContactForm(contactForm);
        }else {
            contactService.updateByForm(contactForm);
            contactDetailService.updateByContactForm(contactForm);
            if (session.getAttribute("contact_page")!=null)
                page = "?page="+ session.getAttribute("contact_page");
        }

        return new ModelAndView("redirect:/contact/list"+page);
    }


}
